package com.zyl.tvolatile;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhaoyl
 * @date 2024/5/20 16:01
 * @description 说明
 */
public class AtomicDemo {
    //volatile 不能保证原子性
    //AtomicInteger 原子类
    private volatile static AtomicInteger num =new AtomicInteger(0);

    public static void add(){

        num.getAndIncrement();// +1 ，原子性操作；CAS 操作
    }

    public static void main(String[] args) {
        //理论上num = 20000
        for (int i =1;i<=20;i++){
            new Thread(()->{
                for (int j=0;j<1000;j++){
                    add();
                }
            }).start();
        }
        //存活线程数量
        while (Thread.activeCount()>2){//默认 main 和 gc
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName()+"->=="+num);
    }
}
